<template>
  <view class="profile-container">
    <!-- 使用新的导航栏组件 -->
    <nav-bar title="个人资料"></nav-bar>

    <!-- 内容区域 -->
    <view class="content-area">
      <!-- 头像 -->
      <view class="profile-item" @tap="uploadAvatar">
        <text class="label">头像</text>
        <view class="avatar-wrapper">
          <image class="avatar" :src="userInfo.avatar || '/static/images/default-avatar.png'" mode="aspectFill"></image>
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>

      <!-- 昵称 -->
      <view class="profile-item" @tap="editNickname">
        <text class="label">昵称</text>
        <view class="value-wrapper">
          <text class="value">{{ userInfo.nickname || '未设置' }}</text>
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>

      <!-- 性别 -->
      <view class="profile-item" @tap="editGender">
        <text class="label">性别</text>
        <view class="value-wrapper">
          <text class="value">{{ genderText }}</text>
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>

      <!-- 生日 -->
      <view class="profile-item" @tap="editBirthday">
        <text class="label">生日</text>
        <view class="value-wrapper">
          <text class="value">{{ userInfo.birthday || '未设置' }}</text>
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>

      <!-- 个性签名 -->
      <view class="profile-item" @tap="editSignature">
        <text class="label">个性签名</text>
        <view class="value-wrapper">
          <text class="value signature">{{ userInfo.signature || '未设置' }}</text>
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getUserInfo, checkLogin } from '@/utils/auth'
import NavBar from '@/components/common/NavBar.vue'

export default {
  components: {
    NavBar
  },
  data() {
    return {
      userInfo: {},
      loading: false
    }
  },
  computed: {
    genderText() {
      const genderMap = {
        1: '男',
        2: '女',
        0: '未设置'
      }
      return genderMap[this.userInfo.gender] || '未设置'
    }
  },
  onShow() {
    // 检查登录状态并加载用户信息
    if (checkLogin()) {
      this.fetchUserProfile()
    } else {
      // 保存当前页面路径
      const pages = getCurrentPages()
      const currentPage = pages[pages.length - 1]
      if (currentPage && currentPage.route) {
        uni.setStorageSync('loginRedirect', `/${currentPage.route}`)
      }
      
      uni.navigateTo({
        url: '/pages/user/auth/login'
      })
    }
  },
  methods: {
    // 从本地存储加载用户信息
    loadUserInfo() {
      this.userInfo = getUserInfo() || {}
    },
    
    // 从服务器获取最新的用户信息
    async fetchUserProfile() {
      if (this.loading) return
      
      this.loading = true
      try {
        const res = await this.$api.user.profile.get()
        if (res.code === 200 && res.data) {
          // 更新本地存储和页面数据
          uni.setStorageSync('userInfo', res.data)
          this.userInfo = res.data
        } else {
          throw new Error(res.message || '获取用户信息失败')
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        uni.showToast({
          title: error.message || '获取用户信息失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    async uploadAvatar() {
      try {
        // 检查登录状态
        if (!checkLogin()) {
          // 保存当前页面路径
          const pages = getCurrentPages()
          const currentPage = pages[pages.length - 1]
          if (currentPage && currentPage.route) {
            uni.setStorageSync('loginRedirect', `/${currentPage.route}`)
          }
          
          uni.navigateTo({
            url: '/pages/user/auth/login'
          })
          return
        }

        // 使用Promise方式选择图片
        const res = await new Promise((resolve, reject) => {
          uni.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success: resolve,
            fail: reject
          })
        })

        const tempFilePath = res.tempFilePaths[0]
        
        // 显示加载提示
        uni.showLoading({
          title: '上传中...',
          mask: true
        })

        try {
          const uploadRes = await this.$api.user.profile.uploadAvatar(tempFilePath)
          
          if (uploadRes.code === 200) {
            // 更新本地用户信息
            const userInfo = getUserInfo()
            userInfo.avatar = uploadRes.data
            uni.setStorageSync('userInfo', userInfo)
            this.userInfo = userInfo

            uni.showToast({
              title: '上传成功',
              icon: 'success'
            })
          } else {
            throw new Error(uploadRes.message || '上传失败')
          }
        } finally {
          // 确保无论成功失败都会隐藏加载提示
          uni.hideLoading()
        }
      } catch (error) {
        // 显示错误提示
        uni.showToast({
          title: error.message || '上传失败',
          icon: 'none'
        })
      }
    },
    
    async updateProfile(data) {
      if (this.loading) return
      
      this.loading = true
      uni.showLoading({
        title: '更新中...',
        mask: true
      })
      
      try {
        const res = await this.$api.user.profile.update(data)
        if (res.code === 200) {
          // 更新成功后重新获取用户信息
          await this.fetchUserProfile()
          
          uni.showToast({
            title: '更新成功',
            icon: 'success'
          })
          return true
        } else {
          throw new Error(res.message || '更新失败')
        }
      } catch (error) {
        console.error('更新个人资料失败:', error)
        uni.showToast({
          title: error.message || '更新失败',
          icon: 'none'
        })
        return false
      } finally {
        uni.hideLoading()
        this.loading = false
      }
    },
    
    editNickname() {
      uni.navigateTo({
        url: '/pages/user/profile/edit?type=nickname&value=' + (this.userInfo.nickname || '')
      })
    },
    
    async editGender() {
      uni.showActionSheet({
        itemList: ['男', '女'],
        success: async (res) => {
          const gender = res.tapIndex + 1
          const success = await this.updateProfile({ gender })
          if (success) {
            // 更新已经在 updateProfile 中完成
            console.log('性别更新成功')
          }
        }
      })
    },
    
    editBirthday() {
      uni.navigateTo({
        url: '/pages/user/profile/edit?type=birthday&value=' + (this.userInfo.birthday || '')
      })
    },
    
    editSignature() {
      uni.navigateTo({
        url: '/pages/user/profile/edit?type=signature&value=' + (this.userInfo.signature || '')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.profile-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-top: calc(var(--status-bar-height) + 88rpx);
}

.content-area {
  margin-top: 20rpx;
  background-color: #fff;
}

.profile-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;

  &:last-child {
    border-bottom: none;
  }

  .label {
    font-size: 28rpx;
    color: #333;
  }

  .avatar-wrapper {
    display: flex;
    align-items: center;

    .avatar {
      width: 100rpx;
      height: 100rpx;
      border-radius: 50%;
      margin-right: 10rpx;
    }
  }

  .value-wrapper {
    display: flex;
    align-items: center;

    .value {
      font-size: 28rpx;
      color: #666;
      margin-right: 10rpx;
      max-width: 400rpx;
      text-align: right;

      &.signature {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}
</style> 